package com.lastoffer2.activity;

import java.util.ArrayList;
import java.util.List;


import com.lastoffer2.R;
import com.lastct.dao.Offer;
import com.lastoffer2.activity.DetailOfferActivity;
import com.lastoffer2.adapter.JobListAdapter;
import com.lastoffer2.util.GeoUtil;
import com.lastoffer2.util.JSONConnector;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class ListOfferActivity extends Activity implements LocationListener,OnItemClickListener {

	protected JobListAdapter adapterList;
	protected List<Offer> data = new ArrayList<Offer>();
	protected ProgressDialog pd;
	protected LocationManager locationManager;
	protected String provider;
	protected Location location;
	protected Location previousLocation;
	protected Criteria criteria;
	protected final Handler handler = new Handler();
	protected Integer userID = Integer.valueOf(-1);
	
	public Integer getUserID() {
		return userID;
	}

	public void setUserID(Integer userID) {
		this.userID = userID;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_offer);
		final ListView lv1 = (ListView) findViewById(R.id.listViewOffer);
		if (savedInstanceState != null) {
			data = (ArrayList<Offer>) savedInstanceState
					.getSerializable("data");
		}
		adapterList = new JobListAdapter(this, data);
		lv1.setAdapter(adapterList);
		// LocationManager service = (LocationManager)
		// getSystemService(LOCATION_SERVICE);
		// boolean enabled = service
		// .isProviderEnabled(LocationManager.GPS_PROVIDER);
		//
		// // Check if enabled and if not send user to the GSP settings
		// // Better solution would be to display a dialog and suggesting to
		// // go to the settings
		// if (!enabled) {
		// Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		// startActivity(intent);
		// }
		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		provider = locationManager.getBestProvider(criteria, false);
		for (String providerTmp : locationManager.getAllProviders()) {
			Location locationTmp = locationManager.getLastKnownLocation(providerTmp);
			if (location != null && location.getTime() + 30000 >= System.currentTimeMillis()) {
				if (locationTmp != null
						&& locationTmp.getAccuracy() > location.getAccuracy()) {
					location = locationTmp;
				}
			} else {
				location = locationTmp;
			}
		}

		if (data.isEmpty()) {
			// Start a new thread that will download all the data
			new DownloadTask()
					.execute("Any parameters my download task needs here");
			this.pd = ProgressDialog.show(this, "Working..",
					"Downloading Data...", true, false);
		}
		
		lv1.setOnItemClickListener(this);
		
		handler.postDelayed( new Runnable() {

		    @Override
		    public void run() {
		    	adapterList.notifyDataSetChanged();
		        handler.postDelayed( this, 60 * 1000 );
		    }
		}, 60 * 1000 );
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);

		savedInstanceState.putSerializable("data", new ArrayList<Offer>(data));
		savedInstanceState.putLong("time", System.currentTimeMillis());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.list_offer, menu);
		return true;
	}

	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, 400, 100, this);
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	@Override
	public void onLocationChanged(Location location) {
		if (location == null) {
			Toast.makeText(this, "Retrived location....updating...",
					Toast.LENGTH_SHORT).show();
		}
		this.previousLocation = this.location;
		this.location = location;
		// Start a new thread that will download all the data
		new DownloadTask().execute("");

	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderEnabled(String provider) {

	}

	@Override
	public void onProviderDisabled(String provider) {
		Toast.makeText(this, "Disabled provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	private class DownloadTask extends AsyncTask<String, Void, Object> {

		protected Object doInBackground(String... args) {
			Log.i("LastOffer", "Background thread starting");
			List<Offer> result = JSONConnector.getListOfferByUserId(userID);
			try {
				if (location != null && !location.equals(previousLocation)) {
					for (Offer offerTmp : result) {
						Location dest = new Location(location);
						dest.setLatitude(offerTmp.getLatitude());
						dest.setLongitude(offerTmp.getLongitude());
						offerTmp.setDistance(GeoUtil.getDistance(location, dest));
					}
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}
			return result;
		}

		protected void onPostExecute(Object result) {
			// Pass the result data back to the main activity
			ListOfferActivity.this.data = (List<Offer>) result;

			ListOfferActivity.this.adapterList
					.dataHasChanged(ListOfferActivity.this.data);
			if (ListOfferActivity.this.pd != null) {
				ListOfferActivity.this.pd.dismiss();
			}
		}

		
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		Offer o=(Offer) adapterView.getItemAtPosition(position);
		Intent i = new Intent(ListOfferActivity.this, DetailOfferActivity.class);
		i.putExtra("IdOffer", o.getIdoffers());
		startActivity(i);
	}

}
